/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			ETSI_Sum.cc
  \date			september 2011
  \author		TNick

  \brief		Contains the implementation for ETSI_Sum class


  Copyright (c) 2011, Nicu Tofan
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 * Neither the name of the copyright holder nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL NICU TOFAN BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include	<QFontMetrics>
#include	<QPainter>
#include	<QPen>

#include	<sheet/ETSheetView.h>
#include	<sheet/ETSheet.h>
#include	<sheet/subitems/ETSI_Root.h>
#include	<sheet/subitems/ETSI_SText.h>

#include	"ETSI_Sum.h"

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */
DDHC_CONTENT(ETSI_Sum)

/* ------------------------------------------------------------------------- */
ETSI_Sum::ETSI_Sum	( void )
	: ETSubItem()
{
	ETSI_SText * only_it;

	only_it = new ETSI_SText();
	top_block.append(only_it);

	only_it = new ETSI_SText();
	btm_block.append(only_it);

	only_it = new ETSI_SText();
	ctr_block.append(only_it);

	top_pos = 0;
	btm_pos = 0;

	DDHC_CONSTRUCT;
	DDHC_SUBITEM_VARS;
	DDHC_VARIABLE(top_pos);
	DDHC_VARIABLE(btm_pos);
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
ETSI_Sum::~ETSI_Sum	( void )
{
	DDHC_DESTRUCT
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void				ETSI_Sum::recalcSign		(void)
{
	QFontMetrics f_m(font());
	setSignSize(f_m.height() * 0.40);
}
/* ========================================================================= */



/* ------------------------------------------------------------------------- */
void				ETSI_Sum::hitTest			(HtData * h_data)
{
	if (ctr_block.hitEmbAid(h_data, 0, 0)) return;
	if (top_block.hitEmbAid(h_data, top_block.posX(), top_pos)) return;
	if (btm_block.hitEmbAid(h_data, btm_block.posX(), btm_pos)) return;

	h_data->it_hitted = this;
	h_data->true_hit = true;
	/* h_data->rct_bbx already set by the caller */
	h_data->int_data = 0;

}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void				ETSI_Sum::paint		(
		ETSheetView * vp, QPainter * painter, QPointF pt_ref )
{

	PaintData	pd(vp, painter, pt_ref);
	prePaint(&pd);

	/* the sigma sign */
	QPen pn_t = painter->pen();
	QPen new_p;
	new_p.setColor(pn_t.color());
	new_p.setCosmetic(false);
	new_p.setCapStyle(Qt::RoundCap);
	new_p.setStyle(Qt::SolidLine);
	new_p.setJoinStyle(Qt::RoundJoin);
	new_p.setWidth(1);

	painter->setPen(new_p);

	const QPointF sigma_p[] = {
		QPointF(pt_ref.x(),						pt_ref.y()-signWidth()),
		QPointF(pt_ref.x() - signWidth(),		pt_ref.y()-signWidth()),
		QPointF(pt_ref.x() - signWidth()/2,		pt_ref.y()),
		QPointF(pt_ref.x() - signWidth(),		pt_ref.y()+signWidth()),
		QPointF(pt_ref.x(),						pt_ref.y()+signWidth())
	};
	painter->drawPolyline(&sigma_p[0], 5);

	painter->setPen(pn_t);



	QPointF bs_p;

	bs_p.setX( pt_ref.x() + top_block.posX() );
	bs_p.setY( pt_ref.y() + top_pos );
	top_block.paint(vp, painter, bs_p);

	bs_p.setX( pt_ref.x() + btm_block.posX() );
	bs_p.setY( pt_ref.y() + btm_pos );
	btm_block.paint(vp, painter, bs_p);

	ctr_block.paint(vp, painter, pt_ref);

	postPaint(&pd);

}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void				ETSI_Sum::recompute	(bool b_full)
{


	if (b_full == false)
	{ /* only recompute if this element is "dirty" */

		/* the SIZE_DIRTY flag means that we should recompute the sigma size
  and all items that rely on this font. */
		if (isSizeDirty())
		{
			top_block.recompute(true);
			ctr_block.recompute(true);
			btm_block.recompute(true);
		}
		else if (isKidSizeDirty())
		{
			if (top_block.requireRecompute())
			{
				top_block.recompute(b_full);
			}
			if (ctr_block.requireRecompute())
			{
				ctr_block.recompute(b_full);
			}
			if (btm_block.requireRecompute())
			{
				btm_block.recompute(b_full);
			}
		}
		else
		{
			return;
		}
	}
	else
	{ /* forced recompute */
		top_block.recompute(b_full);
		ctr_block.recompute(b_full);
		btm_block.recompute(b_full);
	}


	/* get the size of sigma based on the font that is used */
	recalcSign();

	/* the center part has same reference point as this sub-item so
   nothing to do there */

	/* the top and bottom parts must be aligned with sigma sign */

	top_pos = signHeight() * 0.55; /* 0.5 for half */
	qreal	y2_box = top_pos + btm_block.height();
	y2_box = (y2_box > ctr_block.boundingBox().bottom() ?
				  y2_box :
				  ctr_block.boundingBox().bottom());

	btm_pos = top_pos +
			(-1)*btm_block.boundingBox().y(); /* get rid of - sign */
	top_pos = - top_pos -
			(top_block.boundingBox().height() + top_block.boundingBox().y());
	/* horizontal position is aligned with reference point */
	top_block.setPosX(-top_block.width());
	btm_block.setPosX(-btm_block.width());

	qreal	x_bbox = (
				top_block.posX() < btm_block.posX() ?
					top_block.posX() :
					btm_block.posX()
					);
	x_bbox = (x_bbox < -signWidth() ?
				  x_bbox :
				  -signWidth());
	qreal y_box = top_pos + top_block.boundingBox().y();
	y_box = (y_box < ctr_block.boundingBox().y() ?
				 y_box :
				 ctr_block.boundingBox().y());
	bbox = QRectF( QPointF(x_bbox, y_box),
				   QPointF(ctr_block.width(), y2_box ));
	//	QRectF(qreal left, qreal top, qreal width, qreal height);


	/* reset the flags that demand a recompute */
	resetSizeFlags();

}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
ETSI_Sum *		ETSI_Sum::loadXML		(
		QDomElement dom_e)
{

	QDomElement		dom_it;
	ETSI_Sum *	ret_it;

#ifdef	APP_DEBUG
	/* type is assumed to be sum */

	dom_it = dom_e.firstChildElement(XML_TAG_TYPE);
	if (!dom_it.isNull())
	{
		Q_ASSERT_X(dom_it.text() == XML_SIT_SUM, __FUNCTION__,
				   QString("loadXML got an element of type <"
						   "%1> while expected type is " XML_SIT_SUM)
				   .arg(dom_it.text()).toLatin1()
				   );
	}
#endif

	/* create this element */
	ret_it = new ETSI_Sum();


	/* the one and only common data to all kinds of sub-items */
	dom_it = dom_e.firstChildElement(XML_TAG_COMM);
	if (!dom_it.isNull())
	{
		ETSubItem::loadXMLCmn(ret_it, dom_it);

		if (!dom_it.nextSiblingElement(XML_TAG_COMM).isNull())
		{
			qDebug() << "The input presented more than one "
					 << "common tags, when only one per sub-item element "
					 << "is allowed";
		}
	}

	/* load particular data */

	for (;;)
	{
		ETSI_Root::loadEbdXmlRoot(XML_TAG_LIMIT, &ret_it->top_block, dom_e);
		ETSI_Root::loadEbdXmlRoot(XML_TAG_FROM, &ret_it->btm_block, dom_e);
		ETSI_Root::loadEbdXmlRoot(XML_TAG_CONTENT, &ret_it->ctr_block, dom_e);
		return ret_it;
	}
	delete ret_it;
	return NULL;


}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void				ETSI_Sum::saveXML		(
		QDomElement dom_e)
{
	QDomElement dom_it2;

	/* save the type */
	QDomElement dom_it = dom_e.ownerDocument().createElement(XML_TAG_TYPE);
	dom_e.appendChild(dom_it);
	QDomText dom_tx = dom_e.ownerDocument().createTextNode(XML_SIT_FRACT);
	dom_it.appendChild(dom_tx);


	/* save common properties */
	dom_it = dom_e.ownerDocument().createElement(XML_TAG_COMM);
	dom_e.appendChild(dom_it);
	saveXMLCmn(dom_it);


	/* now specifics */
	dom_it = dom_e.ownerDocument().createElement(XML_TAG_LIMIT);
	dom_e.appendChild(dom_it);
	dom_it2 = dom_e.ownerDocument().createElement(XML_TAG_SUBITEM);
	dom_it.appendChild(dom_it2);
	top_block.saveXML(dom_it2);

	dom_it = dom_e.ownerDocument().createElement(XML_TAG_FROM);
	dom_e.appendChild(dom_it);
	dom_it2 = dom_e.ownerDocument().createElement(XML_TAG_SUBITEM);
	dom_it.appendChild(dom_it2);
	btm_block.saveXML(dom_it2);

	dom_it = dom_e.ownerDocument().createElement(XML_TAG_CONTENT);
	dom_e.appendChild(dom_it);
	dom_it2 = dom_e.ownerDocument().createElement(XML_TAG_SUBITEM);
	dom_it.appendChild(dom_it2);
	ctr_block.saveXML(dom_it2);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool		ETSI_Sum::kidNavReq_up		(ETSheetView * vp, ETSubItem * kid)
{
	if (kid == &top_block)
	{
		if (fatherSubI() != NULL)
		{
			fatherSubI()->kidNavReq_up(vp, this);
			return true;
		}
	}
	else if (kid == &btm_block)
	{
		vp->setCurrentSubI(NULL, &top_block);
		return true;
	}

	return false;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool		ETSI_Sum::kidNavReq_down		(ETSheetView * vp, ETSubItem * kid)
{
	if (kid == &top_block)
	{
		vp->setCurrentSubI(NULL, &btm_block);
		return true;
	}
	else if (kid == &btm_block)
	{
		if (fatherSubI() != NULL)
		{
			fatherSubI()->kidNavReq_down(vp, this);
			return true;
		}
	}

	return false;
}
/* ========================================================================= */

/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
